package websocket

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
	"notabug.org/kaya613/huber-go-server/pkg/utils"
)

// type Listener struct {
// 	ws       *websocket.Conn
// 	userName string
// }

//Listeners variable is storage of listeners by chatId
var Listeners = make(map[string]map[*websocket.Conn]string)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

//NewConnection function using on http.HandleFunc
func NewConnection(w http.ResponseWriter, r *http.Request) {
	//connect subscribes list
	var listenChats []string

	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade: ", err)
		return
	}
	defer func() {
		disconnect(c, listenChats)
		c.Close()
	}()

	log.Println("new client:", r.RemoteAddr)

	for {
		//message receiving
		_, messageJSON, err := c.ReadMessage()
		if err != nil {
			log.Print("reader: ", err)
			break
		}

		message, _, err := parseAPIMessage(messageJSON)
		if err != nil {
			log.Println(err)
			break
		}

		message.exec(c, &listenChats)

		utils.Clear()
		for chatID, mapOfListeners := range Listeners {
			fmt.Printf("%s: %d \n", chatID, len(mapOfListeners))
		}
		fmt.Println()
	}
}
